package cool.taomu.toolkit.executor

import com.google.common.util.concurrent.Futures
import com.google.common.util.concurrent.ListenableFuture
import com.google.common.util.concurrent.ListeningExecutorService
import com.google.common.util.concurrent.MoreExecutors
import java.util.ArrayList
import java.util.concurrent.Callable
import java.util.concurrent.Executors
import javax.inject.Inject

class TaomuExecutors<T> {

    ListeningExecutorService executorService

    val static sexecutor = MoreExecutors.listeningDecorator(
        Executors.newScheduledThreadPool(4)
    );

    @Inject
    new(ListeningExecutorService executorService) {
        this.executorService = executorService
    }

    def static <T> getInstance(ListeningExecutorService executorService) {
        new TaomuExecutors<T>(executorService)
    }

    val futures = new ArrayList<ListenableFuture<T>>();

    def tasks(Iterable<Callable<T>> tasks) {
        for (task : tasks) {
            val future = executorService.submit(task)
            futures.add(future)
        }
        this
    }

    def task(Callable<T> task) {
        this.tasks(#[task])
        this
    }

    def execute(Iterable<Runnable> tasks) {
        tasks.forEach [
            executorService.execute(it)
        ]
    }

    def allAsList() {
        new FutureChainBuilder(Futures.allAsList(futures), this.executorService, sexecutor);
    }

    def successfulAsList() {
        new FutureChainBuilder(Futures.successfulAsList(futures), this.executorService, sexecutor);
    }
}
